import { Video, View, Image } from '@tarojs/components'
import { useEffect, useRef, useState, useLayoutEffect, useMemo, memo } from 'react'
import './index.scss'
import Taro from '@tarojs/taro'
import FooterBar from './components/FooterBar'
import RightBar from './components/RightBar'

interface VideoPlayerProps {
  item: Record<string, any>
  isActive: boolean
  index: number
  swiperList: Record<string, any>[]
  commentShow: boolean
  updateSwiperList: (time: number, index: number) => void
  handeleGetList: () => void
  handleUpvote: (tapX: number, tapY: number) => void
}
const VideoPlayer = memo(
  ({
    item,
    isActive,
    index,
    swiperList,
    commentShow,
    updateSwiperList,
    handeleGetList,
    handleUpvote,
  }: VideoPlayerProps) => {
    const videoRef = useRef<any>(null) // 存储视频实例
    const preloadVideoRef = useRef<any>(null) // 预加载视频实例
    const error = useRef(false)
    const currentPlayTime = useRef(0) // 存储当前视频的播放时间
    const [isPlaying, setIsPlaying] = useState(false) // 添加播放状态
    const [preloadVideo, setPreloadVideo] = useState('') // 预加载视频
    const [showVideo, setShowVideo] = useState(false)
    const lastTapTime = useRef(0) // 记录上一次点击的时间
    const TapTimeOut = useRef<NodeJS.Timeout>()
    const Item = useMemo(
      () => ({
        ...item,
      }),
      [item.id]
    ) // 只依赖 item.id 变化

    const handleError = e => {
      console.error('Video error:', e)
      error.current = true
    }

    const handleTap = e => {
      const currentTime = new Date().getTime()
      const tapGap = currentTime - lastTapTime.current
      const tapY = e.detail.y || e.touches?.[0]?.clientY
      const tapX = e.detail.x || e.touches?.[0]?.clientX
      if (tapGap < 300) {
        // 时差小于300ms视为连续点击,清楚单击事件的定时器然后执行连续点击事件
        clearTimeout(TapTimeOut.current)
        handleUpvote(tapX, tapY)
      } else {
        //延迟300ms再执行单击事件
        TapTimeOut.current = setTimeout(() => {
          handlePlay()
        }, 300)
      }
      lastTapTime.current = currentTime
    }

    const handlePlay = () => {
      try {
        if (videoRef.current) {
          if (isPlaying) {
            videoRef.current.pause()
            setIsPlaying(false)
          } else {
            videoRef.current.play()
            setIsPlaying(true)
          }
        }
      } catch (err) {
        console.error('Play error:', err)
      }
    }

    const handleTimeUpdate = e => {
      const { currentTime } = e.detail
      currentPlayTime.current = currentTime
    }

    // 暂停事件
    const handleVideoPause = () => {
      // 更新当前视频项的播放时间
      updateSwiperList(currentPlayTime.current, index)
      setIsPlaying(false)
    }

    useLayoutEffect(() => {
      if (!videoRef.current) {
        videoRef.current = Taro.createVideoContext(`VideoRef_${index}`)
      }
      if (!preloadVideoRef.current) {
        preloadVideoRef.current = Taro.createVideoContext(`PreloadVideo_${index}`)
      }
    }, [])

    // 自动播放当前视频
    useEffect(() => {
      // 处理激活状态变化
      if (videoRef.current) {
        if (isActive) {
          videoRef.current.seek(item.seekTime)
          videoRef.current.play()
          setIsPlaying(true)
        } else {
          videoRef.current.pause()
          setIsPlaying(false)
        }
      }
      // // 预加载下一个视频
      // if (!isActive && index < swiperList.length - 1) {
      //     const nextVideo = swiperList[index + 1]
      //     setPreloadVideo(nextVideo.src)
      //     if (preloadVideoRef.current) {
      //         preloadVideoRef.current.seek(nextVideo.seekTime)
      //         preloadVideoRef.current.play()
      //     }
      // }
      const timer = setTimeout(() => {
        setShowVideo(isActive)
      }, 300)
      return () => clearTimeout(timer)
    }, [isActive])
    // 分页
    useEffect(() => {
      if (index === swiperList.length - 2) {
        handeleGetList()
      }
    }, [index])

    return (
      <>
        <View className="video-box">
          {/* 底部信息栏 */}
          <FooterBar item={Item} />
          {/* 侧边栏 */}
          <RightBar item={Item} />
          <View className={`video_contaier ${commentShow && 'video_hide'}`} onClick={handleTap}>
            {/* 视频播放器 */}
            {isActive && (
              <Video
                style={{
                  opacity: showVideo ? '1' : '0',
                }}
                className="video"
                id={`VideoRef_${index}`}
                src={item.src}
                autoplay={false}
                controls={false}
                showMuteBtn={false}
                enablePlayGesture={false}
                showProgress={false}
                showBottomProgress={false}
                showFullscreenBtn={false}
                showPlayBtn={false}
                showCenterPlayBtn={false}
                loop
                objectFit="cover"
                onTimeUpdate={handleTimeUpdate}
                onPlay={() => setIsPlaying(true)} // 监听播放事件
                onPause={() => handleVideoPause()} // 监听暂停事件
                onEnded={() => setIsPlaying(false)} // 监听结束事件
                onError={handleError}
              />
            )}
            {/* 封面图 */}
            <Image
              className="image"
              style={{
                opacity: !showVideo ? '1' : '0',
              }}
              mode="aspectFill"
              src="https://fastly.picsum.photos/id/866/375/750.jpg?hmac=owU55smBewyf03jO0sqcWIGo2y7J5Q9u3-k_2x6COIw"
            />
            {/* 预加载下一个视频 */}
            {
              // showVideo && (
              //     <Video
              //         id={`PreloadVideo_${index}`}
              //         className="proload_video"
              //         src={preloadVideo}
              //         muted={true}
              //     />
              // )
            }
          </View>
        </View>
      </>
    )
  }
)

export default VideoPlayer
